﻿///<author>Arjen van Zanten</author>
///<datecreated>2012-03-27</datecreated>
///<summary>A processing class that holds static functions for basic Bitmap processing.</summary>

using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Drawing;
using System.Drawing.Imaging;

namespace KentekenHerkenning
{
    public class BitmapProcessor
    {
        /// <summary>
        /// Thresholds the given Bitmap bmp, with the given int threshold.
        /// </summary>
        /// <param name="bmp">Input Bitmap</param>
        /// <param name="threshold">Threshold</param>
        
        public static unsafe void Threshold(Bitmap bmp, int threshold)
        {
            BitmapData bmd = bmp.LockBits(new Rectangle(0, 0, bmp.Width, bmp.Height), ImageLockMode.ReadWrite, PixelFormat.Format32bppArgb);

            byte* p = (byte*)bmd.Scan0;
            int Bpp = bmd.Stride / bmd.Width;
            int totalBytes = bmd.Stride * bmd.Height;
            int grayscaleValue;

            for (int i = 0; i < totalBytes; i += Bpp)
            {
                grayscaleValue = (int)Math.Round((p[i] * 0.11 + p[i + 1] * 0.59 + p[i + 2] * 0.3));
                if (grayscaleValue > threshold)
                {
                    p[i] = p[i + 1] = p[i + 2] = 255;
                }
                else
                {
                    p[i] = p[i + 1] = p[i + 2] = 0;
                }
            }
            bmp.UnlockBits(bmd);
        }
    }
}
